package com.siyoumi.app.modules.sh.service;

import com.siyoumi.app.entity.ShUser;
import com.siyoumi.app.modules.sh.vo.ShListData;
import com.siyoumi.app.service.ShUserService;
import com.siyoumi.component.XRedis;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XJson;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMap;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SvcSh {
    static public SvcSh getBean() {
        return XSpringContext.getBean(SvcSh.class);
    }

    public String rkCodeList() {
        return "sh|code";
    }

    //获取配置的脚本
    public List<ShListData> getListData() {
        RMap<String, String> list = XRedis.getBean().getList(rkCodeList());

        List<ShListData> listData = new ArrayList<>();
        for (Map.Entry<String, String> entry : list.entrySet()) {
            ShListData data = XJson.parseObject(entry.getValue(), ShListData.class);
            data.setId(entry.getKey());
            listData.add(data);
        }

        return listData;
    }

    public ShListData getEntity(String id) {
        String s = XRedis.getBean().getList(rkCodeList()).get(id);
        if (XStr.isNullOrEmpty(s)) {
            return null;
        }
        return XJson.parseObject(s, ShListData.class);
    }


    public XReturn delete(List<String> ids) {
        for (String id : ids) {
            XRedis.getBean().getList(rkCodeList()).remove(id);
        }

        return EnumSys.OK.getR();
    }

    public String shExportConfig() {
        ShUserService app = ShUserService.getBean();
        JoinWrapperPlus<ShUser> query = app.getQuery();
        query.eq("suser_enable", 1);
        List<ShUser> list = app.get(query);

        StringBuilder sb = new StringBuilder();
        String jdCookies = list.stream().map(item -> {
            return XStr.format("pt_key={0};pt_pin={1};", item.getSuser_key(), item.getSuser_share_code());
        }).collect(Collectors.joining("&"));
        sb.append(jdCookies);

        return sb.toString();
    }

}
